package com.cre_drt;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice;
import com.att.intern.webservice.Webservice.TokenInvalidException;

public class ReportSelectionScreen extends ActivityTimeout {
	ProgressDialog progressDialog;
	Spinner eventTypeDropdown;
	Spinner eventYearDropdown;
	Spinner eventNameDropdown;
	ListView incidentList;
	RadioGroup reportRadioGroup;	
	View searchDivider;
	TextView reportSearchHelpHint;

	HashMap<String, String> sessionInfo;
	ArrayList<Incident> searchResults;
	ProgressDialog reportSearchProgressDialog;
	String eventName;

	SessionManager session;
	Webservice searchWebservice;

	HashMap<String, Integer> eventIds = new HashMap<String, Integer>() {
		private static final long serialVersionUID = 1L;
		{
			put("default", R.array.blankDropdown);
			put("hurricaneDropdown2010", R.array.hurricaneDropdown2010);
			put("hurricaneDropdown2011", R.array.hurricaneDropdown2011);
			put("hurricaneDropdown2012", R.array.hurricaneDropdown2012);
			put("hurricaneDropdown2013", R.array.hurricaneDropdown2013);
			put("earthquakeDropdown2010", R.array.earthquakeDropdown2010);
			put("earthquakeDropdown2011", R.array.earthquakeDropdown2011);
			put("earthquakeDropdown2012", R.array.earthquakeDropdown2012);
			put("earthquakeDropdown2013", R.array.earthquakeDropdown2013);
			put("floodDropdown2010", R.array.floodDropdown2010);
			put("floodDropdown2011", R.array.floodDropdown2011);
			put("floodDropdown2012", R.array.floodDropdown2012);
			put("floodDropdown2013", R.array.floodDropdown2013);
			put("ice stormDropdown2010", R.array.iceStormDropdown2010);
			put("ice stormDropdown2011", R.array.iceStormDropdown2011);
			put("ice stormDropdown2012", R.array.iceStormDropdown2012);
			put("ice stormDropdown2013", R.array.iceStormDropdown2013);
			put("snow stormDropdown2010", R.array.snowStormDropdown2010);
			put("snow stormDropdown2011", R.array.snowStormDropdown2011);
			put("snow stormDropdown2012", R.array.snowStormDropdown2012);
			put("snow stormDropdown2013", R.array.snowStormDropdown2013);
			put("tornadoDropdown2010", R.array.tornadoDropdown2010);
			put("tornadoDropdown2012", R.array.tornadoDropdown2011);
			put("tornadoDropdown2012", R.array.tornadoDropdown2012);
			put("tornadoDropdown2013", R.array.tornadoDropdown2013);
			put("wildfireDropdown2010", R.array.wildfireDropdown2010);
			put("wildfireDropdown2011", R.array.wildfireDropdown2011);
			put("wildfireDropdown2012", R.array.wildfireDropdown2012);
			put("wildfireDropdown2013", R.array.wildfireDropdown2013);
		}
	};
	
	HashMap<String, String> reportInfo = new HashMap<String, String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.report_selection_screen);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("Damage Assessment Reporting");
		actionBar.setSubtitle("Select a Report to View");

		session = new SessionManager(getApplicationContext());
		sessionInfo = session.getSessionDetails();

		searchWebservice = new Webservice(getApplicationContext());

		eventYearDropdown = (Spinner) findViewById(R.id.eventYearDropdown);
		eventTypeDropdown = (Spinner) findViewById(R.id.eventTypeDropdown);
		eventNameDropdown = (Spinner) findViewById(R.id.eventNameDropdown);
		incidentList = (ListView) findViewById(R.id.incidentList);
		searchDivider = (View) findViewById(R.id.reportContentSeparator);
		reportSearchHelpHint = (TextView) findViewById(R.id.reportSearchHelpHint);
		
		setUpDropdowns();
		
		reportSearchProgressDialog = new ProgressDialog(this);
		reportSearchProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		reportSearchProgressDialog.setMessage("Searching...");
		reportSearchProgressDialog.setCancelable(false);
	}

	public void setUpDropdowns() {
		eventYearDropdown = (Spinner) findViewById(R.id.eventYearDropdown);
		eventNameDropdown = (Spinner) findViewById(R.id.eventNameDropdown);
		eventTypeDropdown = (Spinner) findViewById(R.id.eventTypeDropdown);

		eventYearDropdown.setSelection(3); // set year to 2013

		String[] eventType = getResources().getStringArray(R.array.eventDropdown);
		ArrayAdapter<String> eventTypeAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, eventType);
		eventTypeDropdown.setAdapter(eventTypeAdapter);

		eventTypeDropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
				String eventNameKey = eventTypeDropdown.getSelectedItem().toString().toLowerCase();

				if (eventNameKey.equalsIgnoreCase("Select Event Type")) {
					eventNameKey = "default";
				} else {
					eventNameKey = eventNameKey + "Dropdown" + eventYearDropdown.getSelectedItem().toString();
				}

				int eventNameId = eventIds.get(eventNameKey);
				String[] eventNames = getResources().getStringArray(eventNameId);
				ArrayAdapter<String> eventNameAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, eventNames);
				eventNameDropdown.setAdapter(eventNameAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		eventYearDropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
				String eventNameKey = eventTypeDropdown.getSelectedItem().toString().toLowerCase();

				if (eventNameKey.equalsIgnoreCase("Select Event Type")) {
					eventNameKey = "default";
				} else {
					eventNameKey = eventNameKey + "Dropdown" + eventYearDropdown.getSelectedItem().toString();
				}

				int eventNameId = eventIds.get(eventNameKey);
				String[] eventNames = getResources().getStringArray(eventNameId);
				ArrayAdapter<String> eventNameAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_style, eventNames);
				eventNameDropdown.setAdapter(eventNameAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}
	
	public void searchForEvent(View view) {
		reportSearchProgressDialog.show();
		new reportSearchAsyncTaskClass().execute();
	}
	
	private class reportSearchAsyncTaskClass extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			eventName = eventNameDropdown.getSelectedItem().toString();
			int eventYear = Integer.valueOf(eventYearDropdown.getSelectedItem().toString());
			searchResults = searchByYearAndName(eventName, eventYear);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			reportSearchProgressDialog.dismiss();
			afterAsyncSearchForEvent();
		}
	}	

	public void afterAsyncSearchForEvent() {
		ArrayList<String> resultList = new ArrayList<String>();				

		if (searchResults.size() > 0) {
			for (Incident item : searchResults) {
				String listItem = "";
				listItem = item.getBuildingName() + "\n";
				listItem = listItem + "Initial Date : " + item.getInitialRptDate() + "\n";
				listItem = listItem + "Status : " + item.getIncidentStatus();
				resultList.add(listItem);
				
				searchDivider.setVisibility(View.VISIBLE);
				reportSearchHelpHint.setVisibility(View.VISIBLE);
			}
		} else {
			if (!eventName.equals("-")) resultList.add("No Reports Found");
			searchDivider.setVisibility(View.INVISIBLE);
			reportSearchHelpHint.setVisibility(View.INVISIBLE);
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultList);
		incidentList.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		
		
		incidentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
				if (searchResults.size() > 0) {
					reportRadioGroup = (RadioGroup) findViewById(R.id.reportRadioGroup);
					int radioID = reportRadioGroup.getCheckedRadioButtonId();
					
					reportInfo.put("eventName", searchResults.get(position).getEventName());
					reportInfo.put("eventYear", String.valueOf(searchResults.get(position).getIncidentYear()));
					reportInfo.put("GLC", String.valueOf(searchResults.get(position).getGeoLoc()));
					reportInfo.put("buildingName", searchResults.get(position).getBuildingName());
					reportInfo.put("propertyType", searchResults.get(position).getBuildingType());
					reportInfo.put("address", searchResults.get(position).getBuildingAddress());
					reportInfo.put("state", searchResults.get(position).getState());
					reportInfo.put("pmATTUID", searchResults.get(position).getPMAttuid());
					reportInfo.put("assessment", searchResults.get(position).getAssessNotes());
					reportInfo.put("status", searchResults.get(position).getStatusNotes());
					reportInfo.put("damaged", searchResults.get(position).getDamageIndicator());
					reportInfo.put("commercialPower", searchResults.get(position).getComPowerIndicator());
					reportInfo.put("onGenerator", searchResults.get(position).getOnGeneratorIndicator());
					reportInfo.put("unOccupiable", searchResults.get(position).getUnOccupiableIndicator());
					reportInfo.put("initialReportDate", searchResults.get(position).getInitialRptDate());
					reportInfo.put("buildingStatus", searchResults.get(position).getBuildingStatus());
					
					Intent getReportIntent = null;
					switch (radioID) {
					case R.id.adminRadio:
						getReportIntent = new Intent(ReportSelectionScreen.this, AdminConditionReportScreen.class);
						break;
					case R.id.buildingRadio:
						getReportIntent = new Intent(ReportSelectionScreen.this, BuildingConditionReportScreen.class);
						break;
					}
					getReportIntent.putExtra("reportInfo", reportInfo);
					startActivity(getReportIntent);
				}
			}
		});
	}

	public ArrayList<Incident> searchByYearAndName(String eventName, int eventYear) {
		ArrayList<Incident> searchResults = new ArrayList<Incident>();
		if (eventName.equals("-")) {
			DialogBox errorDialog = new DialogBox("Please Select a Valid Event", false, getApplicationContext());
			errorDialog.show(getSupportFragmentManager(), "SuccessFragment");
		} else
			try {
				searchResults = searchWebservice.getCREReport(sessionInfo.get(session.KEY_SESSION_TOKEN_ID), eventName, eventYear);
			} catch (TokenInvalidException e) {
				DialogBox invalidTokenWindow = new DialogBox("Invalid TokenID", false, getApplicationContext());
				invalidTokenWindow.show(getSupportFragmentManager(), "ErrorFragment");
			}
		return searchResults;
	}

}